package com.emapp.lccode.utils

import android.util.Log

object XtomLogger {
    private const val ERROR = "The log message is null."
    private const val LENGTH_PER = 4000
    fun println(msg: Any?) {
        println(msg)
    }

    fun v(tag: String, msg: String) {
        log(tag, msg, Level.V)
    }

    fun d(tag: String, msg: String) {
        log(tag, msg, Level.D)
    }

    fun i(tag: String, msg: String) {
        log(tag, msg, Level.I)
    }

    fun w(tag: String, msg: String) {
        log(tag, msg, Level.W)
    }

    @JvmStatic
    fun e(tag: String?, msg: String?) {
        log(tag, msg, Level.E)
    }

    private fun split(msg: String?): ArrayList<String?>? {
        var strings: ArrayList<String?>? = null
        if (msg != null) {
            val length = msg.length
            val count = length / LENGTH_PER
            val remain = length % LENGTH_PER
            strings = ArrayList()
            if (count == 0) strings.add(msg) else {
                for (i in 0 until count) {
                    val start = i * LENGTH_PER
                    val end = start + LENGTH_PER - 1
                    strings.add(msg.substring(start, end))
                }
                if (remain != 0) {
                    val start = count * LENGTH_PER
                    val end = length - 1
                    strings.add(msg.substring(start, end))
                }
            }
        }
        return strings
    }

    private fun log(tag: String?, log: String?, level: Level) {

        // 将字符串分段打印,解决logcat打印不全的问题
        val strings = split(log)
        when (level) {
            Level.V -> if (strings == null) Log.v(
                tag,
                ERROR
            ) else for (string in strings) Log.v(tag, string!!)

            Level.D -> if (strings == null) Log.d(
                tag,
                ERROR
            ) else for (string in strings) Log.d(tag, string!!)

            Level.I -> if (strings == null) Log.i(
                tag,
                ERROR
            ) else for (string in strings) Log.i(tag, string!!)

            Level.W -> if (strings == null) Log.w(
                tag,
                ERROR
            ) else for (string in strings) Log.w(tag, string!!)

            Level.E -> if (strings == null) Log.e(
                tag,
                ERROR
            ) else for (string in strings) Log.e(tag, string!!)
        }
    }

    private enum class Level {
        V, D, I, W, E
    }
}